package com.kyjszj.core.utils;

import com.kyjszj.core.security.utils.Md5Utils;
import com.kyjszj.modules.pinduoduo.entity.PddCategory;
import com.kyjszj.modules.product.entity.Detail;
import com.kyjszj.modules.product.entity.Product;
import com.kyjszj.modules.product.service.IProductService;
import com.kyjszj.modules.spider.SpiderUtils;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgItemCouponGetRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.response.TbkDgItemCouponGetResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.util.*;

public class APIUtils {
    public static final String TAOBAO_URL = "http://gw.api.taobao.com/router/rest";
    public static final String APP_KEY = "24813979";
    public static final String APP_SECRET = "1ed32b99bec3b027d5155d7154ba8e3e";
    public static final long ADZONEID = 284208981L;

    public static final String PINDUODUO = "";


    public static void haoQuanQingDan(IProductService productService) throws ApiException, IOException {
        Long pageCounts = 201L;
        TaobaoClient client = new DefaultTaobaoClient(TAOBAO_URL, APP_KEY, APP_SECRET);
        TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
        req.setAdzoneId(ADZONEID);
        req.setPageSize(50L);
        for (long i = 1; i < pageCounts; i++) {
            List<Product> products = new ArrayList<Product>();
            req.setPageNo(i);
            TbkDgItemCouponGetResponse rsp = client.execute(req);
            JSONObject jsonObject = new JSONObject(rsp.getBody());
            JSONObject object = jsonObject.getJSONObject("tbk_dg_item_coupon_get_response");
            JSONObject results = object.getJSONObject("results");
            JSONArray jsonArray = results.getJSONArray("tbk_coupon");
            for (int j = 0; j < jsonArray.length() - 1; j++) {
                JSONObject jsonObject2 = new JSONObject(jsonArray.get(j).toString());

                if (!jsonObject2.has("zk_final_price")) {
                    continue;
                }
                String zk_final_price = jsonObject2.getString("zk_final_price");

                if (!jsonObject2.has("coupon_remain_count")) {
                    continue;
                }
                int coupon_remain_count = jsonObject2.getInt("coupon_remain_count");

                if (!jsonObject2.has("coupon_total_count")) {
                    continue;
                }
                int coupon_total_count = jsonObject2.getInt("coupon_total_count");

                if (!jsonObject2.has("pict_url")) {
                    continue;
                }
                String pict_url = jsonObject2.getString("pict_url");

                if (!jsonObject2.has("title")) {
                    continue;
                }
                String title = jsonObject2.getString("title");

                if (!jsonObject2.has("coupon_info")) {
                    continue;
                }
                String coupon_info = jsonObject2.getString("coupon_info");

                if (!jsonObject2.has("nick")) {
                    continue;
                }
                String nick = jsonObject2.getString("nick");

                if (!jsonObject2.has("volume")) {
                    continue;
                }
                int volume = jsonObject2.getInt("volume");

                if (!jsonObject2.has("coupon_click_url")) {
                    continue;
                }
                String coupon_click_url = jsonObject2.getString("coupon_click_url");

                if (!jsonObject2.has("user_type")) {
                    continue;
                }
                int user_type = jsonObject2.getInt("user_type");

                if (!jsonObject2.has("item_url")) {
                    continue;
                }
                String item_url = jsonObject2.getString("item_url");

                String num_iid = item_url.split("=")[1];

                if (!jsonObject2.has("shop_title")) {
                    continue;
                }
                String shop_title = jsonObject2.getString("shop_title");

                if (!jsonObject2.has("commission_rate")) {
                    continue;
                }
                String commission_rate = jsonObject2.getString("commission_rate");

                if (!jsonObject2.has("category")) {
                    continue;
                }
                int category = jsonObject2.getInt("category");

                if (!jsonObject2.has("item_description")) {
                    continue;
                }
                String item_description = jsonObject2.getString("item_description");

                if (!jsonObject2.has("coupon_start_time")) {
                    continue;
                }
                String coupon_start_time = jsonObject2.getString("coupon_start_time");

                if (!jsonObject2.has("seller_id")) {
                    continue;
                }
                int seller_id = jsonObject2.getInt("seller_id");

                if (!jsonObject2.has("coupon_end_time")) {
                    continue;
                }
                String coupon_end_time = jsonObject2.getString("coupon_end_time");

                boolean flag = jsonObject2.has("small_images");
                Product product = new Product();
                if (flag) {
                    JSONObject small_images = jsonObject2.getJSONObject("small_images");
                    String smallImages = small_images.get("string").toString();
                    smallImages = smallImages.substring(1, smallImages.length() - 1);
                    product.setSmallImages(smallImages);
                }
                product.setCommissionRate(commission_rate);
                product.setCouponTotalCount(coupon_total_count);
                product.setItemUrl(item_url);
                product.setPictUrl(pict_url);
                product.setNick(nick);
                product.setTitle(title);
                product.setZkFinalPrice(zk_final_price);
                product.setVolume(volume);
                product.setCouponInfo(coupon_info);
                product.setCategory(category);
                product.setShopTitle(shop_title);
                product.setUserType(user_type);
                product.setSellerId(seller_id);
                product.setItemDescription(item_description);
                product.setCouponClickUrl(coupon_click_url);
                product.setCouponEndTime(coupon_end_time);
                product.setNumId(num_iid);
                product.setCouponStartTime(coupon_start_time);
                product.setCouponRemainCount(coupon_remain_count);
                product.setDescription(SpiderUtils.getDescrtion(num_iid));
                products.add(product);
            }
            if (products.size() > 0) {
                productService.insertOrUpdateBatch(products);
                System.out.println("已处理=" + i * 50);
            }

        }

    }

    public static Detail getProduct(String numiid) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(TAOBAO_URL, APP_KEY, APP_SECRET);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setFields("num_iid,title,pict_url,small_images,nick,volume,cat_leaf_name,cat_name,reserve_price,zk_final_price,user_type,provcity,item_url");
        req.setNumIids(numiid);
        TbkItemInfoGetResponse rsp = client.execute(req);
        Detail detail = new Detail();
        JSONObject jsonObject = new JSONObject(rsp.getBody());
        JSONObject object = jsonObject.getJSONObject("tbk_item_info_get_response");
        JSONObject results = object.getJSONObject("results");
        JSONArray jsonArray = results.getJSONArray("n_tbk_item");
        JSONObject jsonObject2 = new JSONObject(jsonArray.get(0).toString());
        boolean flag = jsonObject2.has("small_images");
        String[] test = null;
        if (flag) {
            JSONObject small = jsonObject2.getJSONObject("small_images");
            JSONArray array = small.getJSONArray("string");
            test = new String[array.length()];
            int i = 0;
            for (Object pic : array) {
                test[i] = (String) pic;
                i++;
            }
        }
        detail.setSmall_images(test);
        detail.setItem_url(jsonObject2.getString("item_url"));
        detail.setNick(jsonObject2.getString("nick"));
        detail.setPict_url(jsonObject2.getString("pict_url"));
        detail.setTitle(jsonObject2.getString("title"));
        detail.setUser_type(String.valueOf(jsonObject2.getInt("user_type")));
        detail.setVolume(String.valueOf(jsonObject2.getInt("volume")));
        detail.setZk_final_price(jsonObject2.getString("zk_final_price"));
        detail.setCat_leaf_name(jsonObject2.getString("cat_leaf_name"));
        detail.setNum_iid(numiid);
        detail.setReserve_price(jsonObject2.getString("reserve_price"));
        detail.setProvcity(jsonObject2.getString("provcity"));


        return detail;
    }

    public static List<PddCategory> getPddCategory(){
        List<PddCategory>pddCategories=new ArrayList<PddCategory>();
        Map<String,String>params=new HashMap<String,String>();
        params.put("type","pdd.goods.cats.get");
        params.put("parent_cat_id","0");
        String pddCategoryJson=HttpClientUtil.post(getUrl(params));
        JSONObject jsonObject = new JSONObject(pddCategoryJson);
        JSONObject object = jsonObject.getJSONObject("goods_cats_get_response");
        JSONArray goods_cats_list=object.getJSONArray("goods_cats_list");
        for(int i=0;i<goods_cats_list.length()-1;i++){
            PddCategory pddCategory=new PddCategory();
            JSONObject object1=(JSONObject)goods_cats_list.get(i);
            pddCategory.setCatId(object1.getInt("cat_id")+"");
            pddCategory.setCatName(object1.getString("cat_name"));
            pddCategory.setParentId(object1.getInt("parent_cat_id"));
            pddCategory.setLevel(object1.getInt("level"));
            pddCategories.add(pddCategory);
        }
        return pddCategories;
    }

    /**
     * @Title: sortMap
     * @Description: 对集合内的数据按key的字母顺序做排序
     */
    public static  List<Map.Entry<String, String>> sortMap(Map<String, String> map) {
        final List<Map.Entry<String, String>> infos = new ArrayList<Map.Entry<String, String>>(map.entrySet());

        // 重写集合的排序方法：按字母顺序
        Collections.sort(infos, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(final Map.Entry<String, String> o1, final Map.Entry<String, String> o2) {
                return (o1.getKey().toString().compareTo(o2.getKey()));
            }
        });

        return infos;
    }
    public static List<Map.Entry<String, String>>  getParam(Map<String,String>params){
        params.put("data_type","JSON");
        params.put("client_id",APIInstance.CLIENT_ID);
        params.put("timestamp",System.currentTimeMillis()/1000+"");
        List<Map.Entry<String, String>> lists=APIUtils.sortMap(params);
        return  lists;
    }
    public static String  getSign(Map<String,String>params){
        String sign=APIInstance.CLIENT_SECRET;
        List<Map.Entry<String, String>> lists=APIUtils.getParam(params);
        for(final  Map.Entry<String, String> m:lists){
            sign+=m.getKey();
            sign+=m.getValue();
        }
        return   Md5Utils.hash(sign+APIInstance.CLIENT_SECRET).toUpperCase();
    }
    public static String getUrl(Map<String,String>params){
        String sign=getSign(params);
        String url=APIInstance.PDD_URL+"?";
        for(final  Map.Entry<String, String> m:getParam(params)){
            url+=m.getKey()+"=";
            url+=m.getValue()+"&";
        }
       url+="sign="+sign;
        return url;
    }


    public static void main(String[] args)  {
        System.out.println(getPddCategory());

    }


}
